package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAllRoles() {
        return roleDao.findAllRoles();
    }

    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage, pageSize);
        Page<Role> page = roleDao.fingByCondition(queryString);
        long total = page.getTotal();
        List<Role> rows = page.getResult();
        return new PageResult(total, rows);
    }


    @Override
    public Role findByRoleId(Integer id) {
        return roleDao.findByRoleId(id);
    }

    public void setRoleAndPermission(Integer roleId, Integer[] permissionIds) {
        if (permissionIds != null && permissionIds.length > 0) {
            for (Integer permissionId : permissionIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("roleId", roleId);
                map.put("permissionId", permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }

    @Override
    public void edit(Integer[] permissionIds, Role role) {
        Integer id = role.getId();
        roleDao.deleRoleIdAndPermissionId(id);
        this.setRoleAndPermission(id, permissionIds);
        roleDao.edit(role);
    }


    @Override
    public void delete(Integer id) {
        roleDao.deleRoleIdAndPermissionId(id);
        roleDao.deleteRoleAndMenu(id);
        roleDao.deleteRoleAndUser(id);
        roleDao.delete(id);
    }

    @Override
    public void add(Role role, Integer[] permissionIds) {
        //新增检查组，操作t_role表
        roleDao.add(role);
        //设置角色表和权限表的多对多的关联关系，操作t_role_permission表
        Integer roleId = role.getId();
        this.setRoleAndPermission(roleId, permissionIds);

    }

    @Override
    public List<Role> findAllRole() {
        return roleDao.findAllRole();
    }
}
